package com.wsoft.hr.pm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.bpm.enums.ApproveStatus;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.entity.HrPmActivityEntity;
import com.wsoft.hr.pm.entity.HrPmCycleEntity;
import com.wsoft.hr.pm.entity.HrPmWarningEntity;
import com.wsoft.hr.pm.enums.WarningTypeEnum;
import com.wsoft.hr.pm.manager.HrPmActivityManager;
import com.wsoft.hr.pm.manager.HrPmCycleManager;
import com.wsoft.hr.pm.manager.HrPmWarningManager;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程阻断预警 - 判断次月考核活动是否提交
 * @Author z001
 * @Date 2025/3/8 08:17
 */
@Service
public class MonthActivityJob implements Job {

    @Resource
    private HrPmCycleManager cycleManager;
    @Resource
    private HrPmActivityManager activityManager;
    @Resource
    private HrPmWarningManager warningManager;
    @Resource
    private CommonFreemarkerService freemarkerService;

    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "freemarker_code";


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail job = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = job.getJobDataMap();
        //任务参数
        Object jobParam = jobDataMap.get(CommonConstant.JOB_PARAMS);
        if (ObjUtil.isNull(jobParam)) {
            return;
        }
        JSONObject param = JSONObject.parseObject(jobParam.toString());
        //获取模版code
        Object freemarkerCode = param.get(FREEMARKER_CODE);
        if (null == freemarkerCode) {
            return;
        }

        String nextMonth = getNextMonthDate();

        //获取下个月的周期
        List<HrPmCycleEntity> cycleEntities = cycleManager.likeExpireDate(nextMonth);
        if(CollUtil.isNotEmpty(cycleEntities)){
            //判断下个月周期中有没有活动,没有则预警
            List<Long> cycleIdList = cycleEntities.stream().map(BaseEntity::getId).collect(Collectors.toList());

            //查询不是 审批完成的
            List<HrPmActivityEntity> entities = activityManager.listByCyclesNotStatus(cycleIdList, ApproveStatus.APPROVED.getValue());
            if(CollUtil.isNotEmpty(entities)){

                List<HrPmWarningEntity> warningList = new ArrayList<>();
                for (HrPmActivityEntity entity : entities) {
                    HrPmWarningEntity warning = new HrPmWarningEntity();
                    warning.setTitle(buildFreemarkerMap(nextMonth, freemarkerCode));
                    warning.setType(WarningTypeEnum.PROCESS_BLOCKAGE.getType());
                    warning.setHrOrgId(entity.getHrOrgId());
                    warning.setOpenType("component");
                    warning.setOpenPage("");
                    warningList.add(warning);
                }
                warningManager.saveBatch(warningList);
            }
        }
    }



    /**
     * 构建freemarker模板
     * @param nextMonth
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(String nextMonth, Object freemarkerCode){
        Map<String,Object> map = new HashMap<>(3);
        map.put("nextMonth",nextMonth);
        //${nextMonth}月度绩效考核活动尚未提交，即将超时，请及时开启。
        return freemarkerService.sendTextTemplate(freemarkerCode.toString(), map,true);
    }

    /**
     * 获取当前时间的下个月日期，格式为 yyyy-MM
     *
     * @return 下个月的日期，格式为 yyyy-MM
     */
    public static String getNextMonthDate() {
        // 获取当前时间
        Date now = DateUtil.date();

        // 获取下个月的日期
        Date nextMonth = DateUtil.offsetMonth(now, 1);

        // 格式化为 yyyy-MM
        return DateUtil.format(nextMonth, "yyyy-MM");
    }
}
